//
//  Gailan_vc.m
//  ainkjj
//
//  Created by MAX on 2020/4/20.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Gailan_vc.h"
#import "Jiankang_fenxi_vc.h"
#import "Huati_taolun_fabu_vc.h"
#import "Huati_guangchang_vc.h"
#import "Tuijian_vc.h"
#import "Tiezi_fabu_vc.h"
#import "Tiezi_xiangqing_vc.h"
#import "Tiezi_pinglun_vc.h"


#import "App_devices_model.h"
#import "BB_bed_Info.h"
#import "Bmi_setBabyBmi.h"
#import "Gailan_grid_sub_view.h"
#import "CYLPlusDemoChildViewController.h"
#import "Music_page_list_vc.h"
#import "GailanPagerVc.h"



static CGFloat const kLeftInset = 16;

@interface Gailan_vc ()<Jiankang_fenxi_delegate>
@property (nonatomic, strong)UIScrollView *sv;

@property(nonatomic, strong) QMUIPopupMenuView *popupByWindow;
@property(nonatomic, strong) QMUIButton *shebei_caidan_btn;


@property(nonatomic, strong) QMUIGridView *gridView;
@property (nonatomic, strong)QMUILabel *wenxintishiLb;
@property (nonatomic, strong)App_devicesData *currentDevice;
@property (nonatomic, strong)BB_bed_Info *current_bb_bed_info;
@property (nonatomic, strong)Bmi_setBabyBmi *current_bmi;

@property (nonatomic, strong)UILabel *bb_title_lb;
@property (nonatomic, strong)UILabel *bb_st_lb;
@property (nonatomic, strong)UILabel *bb_xq_lb;
@property (nonatomic, strong)UILabel *shuimian_shichang_lb;
@property (nonatomic, strong)QMUIButton *add_device_btn;


@property (nonatomic, strong)QMUIButton *qu_geng_xin_btn;
@end

@implementation Gailan_vc
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 请求数据
    [self req_devices];
    

//    [self presentPanModal:[Music_page_list_vc new]];
}
- (void)setCurrentDevice:(App_devicesData *)currentDevice{
    _currentDevice = currentDevice;
    
    if (currentDevice.device_id == nil) {
        [self.shebei_caidan_btn setTitle:@"无设备" forState:UIControlStateNormal];
        self.bb_xq_lb.text = @"您还未添加设备";
        self.add_device_btn.hidden = NO;
        self.current_bb_bed_info = nil;
        self.current_bmi = nil;
    }else{
        // 请求新的bmi和bed 数据
        self.bb_xq_lb.text = @"您的宝宝基本信息还未添加，为更好掌握宝宝健康状况，请及时添加！";

        [self.shebei_caidan_btn setTitle:currentDevice.device_name forState:UIControlStateNormal];
        [self req_bb_bed];
        [self req_bmi_info];
    }
}
- (void)setCurrent_bb_bed_info:(BB_bed_Info *)current_bb_bed_info{
    _current_bb_bed_info = current_bb_bed_info;
    
    // 睡眠呵护与温馨提示
    
    
    NSMutableArray *cishuAttr = [NSMutableArray array];
    NSMutableArray *shijianArr = NSMutableArray.new;
    
    

    if (current_bb_bed_info.data == nil) {
        if (self.currentDevice) {
            self.wenxintishiLb.text = @"暂无数据";
        }else{
            self.wenxintishiLb.text = @"您还未添加设备";

        }
        shijianArr = @[@"", @"", @"", @""].mutableCopy;
        
        [cishuAttr addObject:[Anktool begin:@"睡眠  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(0).stringValue cishu_numFontSize:18 cishu_num_textColor:rgb(5,228,189) shegnjiang_img:@""]];

        [cishuAttr addObject:[Anktool begin:@"尿床  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(0).stringValue cishu_numFontSize:18 cishu_num_textColor:rgb(5,228,189) shegnjiang_img:@""]];

        [cishuAttr addObject:[Anktool begin:@"夜灯  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(0).stringValue cishu_numFontSize:18 cishu_num_textColor:rgb(5,228,189) shegnjiang_img:@""]];
        [cishuAttr addObject:[Anktool begin:@"踢被  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(0).stringValue cishu_numFontSize:18 cishu_num_textColor:rgb(5,228,189) shegnjiang_img:@""]];

      
        
    }else{
        
        if ([NSString stringWithFormat:@"%@%@%@%@", current_bb_bed_info.data.sleepAnalyze, current_bb_bed_info.data.enuresisAnalyze, current_bb_bed_info.data.nightLightAnalyze, current_bb_bed_info.data.quiltAnalyze].length == 0) {
            self.wenxintishiLb.text = @"暂无数据";
        }else{
            self.wenxintishiLb.text = [NSString stringWithFormat:@"%@\n %@\n %@\n %@\n", current_bb_bed_info.data.sleepAnalyze, current_bb_bed_info.data.enuresisAnalyze, current_bb_bed_info.data.nightLightAnalyze, current_bb_bed_info.data.quiltAnalyze];
        }
        
        
        
        
        [shijianArr addObject:current_bb_bed_info.data.finallySleepData];
        [shijianArr addObject:current_bb_bed_info.data.finallyEnuresisData];
        [shijianArr addObject:current_bb_bed_info.data.finallyNightLightData];
        [shijianArr addObject:current_bb_bed_info.data.finallyQuiltData];
        
        
        {
            UIColor *textColor = rgb(5,228,189);
            NSString *imgName = @"";
            if ([current_bb_bed_info.data.sleepTimeSort isEqualToString:@"asc"]) {
                textColor = rgb(240,54,93);
                imgName = @"up_arrow_icon";
            }else if ([current_bb_bed_info.data.sleepTimeSort isEqualToString:@"desc"]){
                textColor = rgb(5,228,189);
                imgName = @"down_arrow_icon";
            }else if ([current_bb_bed_info.data.sleepTimeSort isEqualToString:@"equal"]){
                textColor = rgb(5,228,189);
            }
            [cishuAttr addObject:[Anktool begin:@"睡眠  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(current_bb_bed_info.data.sleepTime).stringValue cishu_numFontSize:18 cishu_num_textColor:textColor shegnjiang_img:imgName]];
            
        }
        
        {
            UIColor *textColor = rgb(5,228,189);
            NSString *imgName = @"";
            if ([current_bb_bed_info.data.enuresisSort isEqualToString:@"asc"]) {
                textColor = rgb(240,54,93);
                imgName = @"up_arrow_icon";
            }else if ([current_bb_bed_info.data.enuresisSort isEqualToString:@"desc"]){
                textColor = rgb(5,228,189);
                imgName = @"down_arrow_icon";
            }else if ([current_bb_bed_info.data.enuresisSort isEqualToString:@"equal"]){
                textColor = rgb(5,228,189);
            }
            [cishuAttr addObject:[Anktool begin:@"尿床  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(current_bb_bed_info.data.enuresisTime).stringValue cishu_numFontSize:18 cishu_num_textColor:textColor shegnjiang_img:imgName]];
            
        }
        
        {
            UIColor *textColor = rgb(5,228,189);
            NSString *imgName = @"";
            if ([current_bb_bed_info.data.nightLightSort isEqualToString:@"asc"]) {
                textColor = rgb(240,54,93);
                imgName = @"up_arrow_icon";
            }else if ([current_bb_bed_info.data.nightLightSort isEqualToString:@"desc"]){
                textColor = rgb(5,228,189);
                imgName = @"down_arrow_icon";
            }else if ([current_bb_bed_info.data.nightLightSort isEqualToString:@"equal"]){
                textColor = rgb(5,228,189);
            }
            [cishuAttr addObject:[Anktool begin:@"夜灯  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(current_bb_bed_info.data.nightLightTime).stringValue cishu_numFontSize:18 cishu_num_textColor:textColor shegnjiang_img:imgName]];
            
        }
        
        {
            UIColor *textColor = rgb(5,228,189);
            NSString *imgName = @"";
            if ([current_bb_bed_info.data.quiltSort isEqualToString:@"asc"]) {
                textColor = rgb(240,54,93);
                imgName = @"up_arrow_icon";
            }else if ([current_bb_bed_info.data.quiltSort isEqualToString:@"desc"]){
                textColor = rgb(5,228,189);
                imgName = @"down_arrow_icon";
            }else if ([current_bb_bed_info.data.quiltSort isEqualToString:@"equal"]){
                textColor = rgb(5,228,189);
            }
            [cishuAttr addObject:[Anktool begin:@"踢被  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(current_bb_bed_info.data.quiltTime).stringValue cishu_numFontSize:18 cishu_num_textColor:textColor shegnjiang_img:imgName]];
            
        }
    }
    
    for (NSInteger i = 0; i < self.gridView.subviews.count; i++) {
        Gailan_grid_sub_view *view = self.gridView.subviews[i];
        view.shijian_lb.text = shijianArr[i];
        view.cishuLb.attributedText = cishuAttr[i];
//        DLog(@"%@%@", shijianArr[i], cishuAttr[i]);
    }
    
    
    self.wenxintishiLb.frame = CGRectMake(kLeftInset, CGRectGetMaxY(self.gridView.frame)   + kLeftInset + 30 , self.gridView.mj_w, QMUIViewSelfSizingHeight);
    [self.sv setContentSize:CGSizeMake(ScreenWidth, CGRectGetMaxY(self.wenxintishiLb.frame) + 20)];
}
- (void)setCurrent_bmi:(Bmi_setBabyBmi *)current_bmi{
    _current_bmi = current_bmi;
    
    if (current_bmi.data) {
        if ([Anktool strIsBlank:current_bmi.data.name]) {
            self.bb_title_lb.attributedText = [self bb_title:[NSString stringWithFormat:@"宝宝现在已经%@了哦", [self bb_month]] font:[UIFont boldSystemFontOfSize:20.0f]];

        }else{
            self.bb_title_lb.attributedText = [self bb_title:[NSString stringWithFormat:@"%@现在已经%@了哦", current_bmi.data.name, [self bb_month]] font:[UIFont boldSystemFontOfSize:20.0f]];

        }
        self.bb_st_lb.attributedText = [self bb_title:[NSString stringWithFormat:@"身高%.2fcm  体重%.2fkg", current_bmi.data.height, current_bmi.data.weight] font:[UIFont boldSystemFontOfSize:18.0f]];
        [self.bb_st_lb setAdjustsFontSizeToFitWidth:YES];
        //        self.bb_xq_lb.text = current_bmi.data.heightAnalyze;
        
        self.bb_xq_lb.text = [current_bmi.data.heightAnalyze stringByAppendingString:current_bmi.data.weightAnalyze];
        
        self.add_device_btn.hidden = YES;
        self.qu_geng_xin_btn.hidden = NO;
    }else{
        self.bb_title_lb.text = @"";
        self.bb_st_lb.text = @"";
        self.qu_geng_xin_btn.hidden = YES;
        if (![self.bb_xq_lb.text isEqualToString:@"您还未添加设备"]) {
            self.bb_xq_lb.text = @"您的宝宝基本信息还未添加，为更好掌握宝宝健康状况，请及时添加！";
            self.add_device_btn.hidden = NO;
            
        }
       
        
    }
    
    CGSize bb_xq_size = [self.bb_xq_lb sizeThatFits:CGSizeMake(self.bb_xq_lb.bounds.size.width, CGFLOAT_MAX)];
    self.bb_xq_lb.frame = CGRectMake(self.bb_xq_lb.mj_origin.x, self.bb_xq_lb.mj_origin.y, self.bb_xq_lb.mj_w, bb_xq_size.height);
}


- (void)req_devices{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"app_code"];
    [dict setObject:self.category_id forKey:@"category_id"];

    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    
    [PPHTTPRequest req:@"api/App/devices" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            App_devices_model *data = [App_devices_model mj_objectWithKeyValues:response];
            if (data.data.count > 0) {
                
                // 更新菜单
                NSMutableArray *arr = NSMutableArray.new;
                for (App_devicesData *aDev in data.data) {
                    QMUIPopupMenuButtonItem *it = [QMUIPopupMenuButtonItem itemWithImage:nil title:aDev.device_name handler:^(QMUIPopupMenuButtonItem *aItem) {
                        [aItem.menuView hideWithAnimated:YES];
                        if (![aItem.deviceId isEqualToString:self.currentDevice.device_id]) {
                            
                            for (App_devicesData *d in data.data) {
                                if ([d.device_id isEqualToString:aItem.deviceId]) {
                                    self.currentDevice = d;
                                    [self.shebei_caidan_btn setTitle:d.device_name forState:UIControlStateNormal];
                                }
                            }
                            
                        }
                    }];
                    it.deviceId = aDev.device_id;
                    [arr addObject:it];
                }
                
                self.popupByWindow.items = arr;
                
                
                // 之前的设备还在吗
                
                for (App_devicesData *aDev in data.data) {
                    if ([self.currentDevice.device_id isEqualToString:aDev.device_id]) {
                        self.currentDevice = aDev;
                        return;
                    }
                }
                
                // 之前的不在了
                
                self.currentDevice = data.data.firstObject;
                

            }else{
                
                self.currentDevice = nil;
                self.popupByWindow.items = @[];

            }
            
           
        }
        
        else
            //            if ([error_code isEqualToString:@""])
        {
            
            [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
            
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showTipMessageInView:[error localizedDescription]];
        
    }];
}
- (void)req_bb_bed{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:self.currentDevice.device_id forKey:@"deviceId"];
    
    //sender.userInteractionEnabled = NO;
    
    
    [PPHTTPRequest req:@"java/app/device/getBabySleepInfo" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            BB_bed_Info *bb_bed_info = [BB_bed_Info mj_objectWithKeyValues:response];
            self.current_bb_bed_info = bb_bed_info;
            
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"] ];
            
        }
        
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription]];
        
    }];
}
- (void)req_bmi_info{
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:self.currentDevice.device_id forKey:@"deviceId"];
    
    //sender.userInteractionEnabled = NO;
//    __block QMUITips *qmui_tip = [QMUITips showLoading:@"请求中..." inView:self.navigationController.view];
    
    [PPHTTPRequest req:@"java/app/bmi/getBabyBmi" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            
            self.current_bmi = [Bmi_setBabyBmi mj_objectWithKeyValues:response];
            
            
            
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"]];
            
        }
        
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription] ];
        
    }];
}


- (void)initSubviews{
    [super initSubviews];
    self.view.backgroundColor = RGBA(247,247,247, 1);
    GailanPagerVc *pvc = (GailanPagerVc *)self.parentViewController;
    
    UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight -  Lzy_TabbarHeight - pvc.titleLb_maxY - 44)];
    [self.view addSubview:sv];
    sv.backgroundColor = self.view.backgroundColor;
    self.sv = sv;
//    [self.sv setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
//    UILabel *shouye_tip = [[UILabel alloc] initWithFrame:CGRectMake(kLeftInset, 64, 100, 36)];
//    [self.sv addSubview:shouye_tip];
//    shouye_tip.text = @"首页";
//    shouye_tip.textColor = appMainColor;
//    shouye_tip.font = [UIFont boldSystemFontOfSize:36];
//    CGSize shouye_tip_size = [shouye_tip sizeThatFits:CGSizeMake(CGFLOAT_MAX, 36)];
//    shouye_tip.frame = CGRectMake(shouye_tip.mj_origin.x, shouye_tip.mj_origin.y, shouye_tip_size.width, shouye_tip_size.height);
    // 婴儿床 菜单
    
    
    self.shebei_caidan_btn = [QDUIHelper generateLightBorderedButton];
    [self.shebei_caidan_btn addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.shebei_caidan_btn setTitle:@"无设备" forState:UIControlStateNormal];
    [sv addSubview:self.shebei_caidan_btn];
    [self.shebei_caidan_btn setImage:UIImageMake(@"main_drop_down_icon") forState:UIControlStateNormal];
    [self.shebei_caidan_btn setImagePosition:QMUIButtonImagePositionRight];
    [self.shebei_caidan_btn setSpacingBetweenImageAndTitle:4];
    
    self.shebei_caidan_btn.frame = CGRectMake(kLeftInset, 10 , 120, 40);
    
    __weak __typeof(self) weakSelf = self;
    // 使用方法 2，以 UIWindow 的形式显示到界面上，这种无需默认隐藏，也无需 add 到某个 UIView 上
    self.popupByWindow = [[QMUIPopupMenuView alloc] init];
    self.popupByWindow.automaticallyHidesWhenUserTap = YES;// 点击空白地方消失浮层
    [self.popupByWindow setPreferLayoutDirection:QMUIPopupContainerViewLayoutDirectionBelow];
    self.popupByWindow.maskViewBackgroundColor = UIColorMaskWhite;// 使用方法 2 并且打开了 automaticallyHidesWhenUserTap 的情况下，可以修改背景遮罩的颜色
    self.popupByWindow.shouldShowItemSeparator = YES;
    self.popupByWindow.itemConfigurationHandler = ^(QMUIPopupMenuView *aMenuView, QMUIPopupMenuButtonItem *aItem, NSInteger section, NSInteger index) {
        // 利用 itemConfigurationHandler 批量设置所有 item 的样式
        aItem.button.highlightedBackgroundColor = [UIColor.qd_tintColor colorWithAlphaComponent:.2];
        [aItem.button setTitleColor:appMainColor forState:UIControlStateNormal];
    };
   
    self.popupByWindow.didHideBlock = ^(BOOL hidesByUserTap) {
        //        [weakSelf.shebei_caidan_btn setTitle:@"显示菜单浮层" forState:UIControlStateNormal];
    };
    self.popupByWindow.sourceView = self.shebei_caidan_btn;// 相对于 button4 布局
    
    
    
    
    
    
    UIImageView *bgIv = [[UIImageView alloc] initWithFrame:CGRectMake(kLeftInset, CGRectGetMaxY(_shebei_caidan_btn.frame) + 10, ScreenWidth - 2 * kLeftInset, (ScreenWidth - 2 * kLeftInset) * 160 / 343.0)];
    [sv addSubview:bgIv];
    bgIv.image = [Anktool gradient_img_create:rgb(255,186,187) toColor:rgb(251,119,160) frame:bgIv.frame];
    bgIv.layer.cornerRadius = 20;
    bgIv.layer.masksToBounds = YES;
    bgIv.userInteractionEnabled = YES;
    
    UIImageView *tip_bg_iv = [[UIImageView alloc] initWithImage:UIImageMake(@"main_img")];
    [bgIv addSubview:tip_bg_iv];
    tip_bg_iv.frame = CGRectMake(CGRectGetWidth(bgIv.frame) - tip_bg_iv.bounds.size.width, CGRectGetHeight(bgIv.frame) - tip_bg_iv.bounds.size.height, tip_bg_iv.bounds.size.width, tip_bg_iv.bounds.size.height);
    
    UILabel *bb_title_lb = [[UILabel alloc] initWithFrame:CGRectMake(kLeftInset, 10, CGRectGetWidth(bgIv.frame) - 2 * kLeftInset -70, 30)];
    [bgIv addSubview:bb_title_lb];
    self.bb_title_lb = bb_title_lb;
    //10
    NSString *raw_bb_title = @"";
    
    
    bb_title_lb.attributedText = [self bb_title:raw_bb_title font:[UIFont boldSystemFontOfSize:20.0f]];
    
    QMUIButton *qgx_btn = [QDUIHelper generateLightBorderedButton];
    [qgx_btn setTitle:@"去更新" forState:UIControlStateNormal];
    qgx_btn.frame = CGRectMake(CGRectGetMaxX(bb_title_lb.frame) +10, CGRectGetMinY(bb_title_lb.frame) - 4, 70, CGRectGetHeight(bb_title_lb.frame) + 4);
    self.qu_geng_xin_btn = qgx_btn;
    [qgx_btn addTarget:self action:@selector(qu_geng_xin_btn_action) forControlEvents:UIControlEventTouchUpInside];
    [bgIv addSubview:qgx_btn];
    qgx_btn.layer.cornerRadius = CGRectGetHeight(qgx_btn.frame) * 0.5;
    self.qu_geng_xin_btn.hidden = YES;

    
    UILabel *bb_st_lb = [[UILabel alloc] initWithFrame:CGRectMake(kLeftInset, CGRectGetMaxY(bb_title_lb.frame), CGRectGetWidth(bgIv.frame) - kLeftInset - tip_bg_iv.bounds.size.width, 30)];
    self.bb_st_lb = bb_st_lb;
    [bgIv addSubview:bb_st_lb];
    //10
    NSString *raw_bbst_title = @"";
    
    bb_st_lb.attributedText = [self bb_title:raw_bbst_title font:[UIFont boldSystemFontOfSize:18.0f]];;
    
    UILabel *bb_xq_lb = [[UILabel alloc] initWithFrame:CGRectMake(kLeftInset, CGRectGetMaxY(bb_st_lb.frame) + 4, CGRectGetWidth(bgIv.frame) - kLeftInset - tip_bg_iv.bounds.size.width, 30)];
    [bgIv addSubview:bb_xq_lb];
    self.bb_xq_lb = bb_xq_lb;
    bb_xq_lb.numberOfLines = 5;
    bb_xq_lb.text = @"";
    bb_xq_lb.font = [UIFont systemFontOfSize:14];
    bb_xq_lb.textColor = UIColor.whiteColor;
    [self.bb_xq_lb setTextAlignment:NSTextAlignmentCenter];

    [self.add_device_btn setTitle:@"去添加" forState:UIControlStateNormal];
    self.add_device_btn.hidden = YES;
    self.add_device_btn.frame = CGRectMake((bb_xq_lb.mj_w - 100) * 0.5 + bb_xq_lb.mj_x, CGRectGetMaxY(bb_xq_lb.frame )+ 16, 100, 40);
    [bgIv addSubview:self.add_device_btn];
    
    
    UIView *v1_v = [[UIView alloc] initWithFrame:CGRectMake(kLeftInset, CGRectGetMaxY(bgIv.frame) + kLeftInset, 4, 16)];
    [sv addSubview:v1_v];
    
    v1_v.layer.masksToBounds = YES;
    v1_v.layer.cornerRadius = 2;
    v1_v.backgroundColor = themeColor;
    
    UILabel *v1_lb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(v1_v.frame) + 10, CGRectGetMinY(v1_v.frame), 100,30)];
    v1_lb.center = CGPointMake(v1_lb.center.x, v1_v.center.y);
    [sv addSubview:v1_lb];
    //
    NSMutableAttributedString *v1_lb_attr_str = [[NSMutableAttributedString alloc] initWithString:@"睡眠呵护"];
    [v1_lb_attr_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFang-SC-Medium" size:17.0f] range:NSMakeRange(0, 4)];
    [v1_lb_attr_str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:17.0f/255.0f green:17.0f/255.0f blue:17.0f/255.0f alpha:1.0f] range:NSMakeRange(0, 4)];
    v1_lb.attributedText = v1_lb_attr_str;
    
    
    UILabel *shuimian_shichang_lb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(v1_lb.frame), CGRectGetMinY(v1_lb.frame), ScreenWidth - kLeftInset - CGRectGetMaxX(v1_lb.frame), v1_lb.mj_h)];
    [sv addSubview:shuimian_shichang_lb];
    self.shuimian_shichang_lb = shuimian_shichang_lb;
    shuimian_shichang_lb.font = [UIFont systemFontOfSize:14];
    shuimian_shichang_lb.textColor = rgb(153,153,153);
    shuimian_shichang_lb.text = @"近24小时睡眠时间：";
    [shuimian_shichang_lb setTextAlignment:NSTextAlignmentRight];
    
    
    
    self.gridView = [[QMUIGridView alloc] init];
    self.gridView.columnCount = 2;
    self.gridView.rowHeight = 100;
    self.gridView.separatorWidth = 10;
    self.gridView.separatorColor = self.view.backgroundColor;
//    self.view.backgroundColor = UIColorSeparator;
    self.gridView.separatorDashed = NO;
    [self.sv addSubview:self.gridView];
    
    // 将要布局的 item 以 addSubview: 的方式添加进去即可自动布局
    NSArray *imgNameArr = @[@"sleep_icon", @"bed_wetting_icon", @"night_light_icon", @"kick_quilt_icon"];
    
    for (NSInteger i = 0; i < imgNameArr.count; i++) {
        Gailan_grid_sub_view *view = [[Gailan_grid_sub_view alloc] initWithFrame:CGRectMake(0, 0, (ScreenWidth - 2 * kLeftInset - 10) * 0.5, 100)];
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius = 5;
        view.iv.image = UIImageMake(imgNameArr[i]);
        
        view.backgroundColor = UIColor.whiteColor;
        [self.gridView addSubview:view];
    }
    
    self.gridView.frame = CGRectMake(kLeftInset, CGRectGetMaxY(shuimian_shichang_lb.frame) + 10, ScreenWidth - 2 * kLeftInset, QMUIViewSelfSizingHeight);
    
    
    UIView *v2_v = [[UIView alloc] initWithFrame:CGRectMake(kLeftInset, CGRectGetMaxY(self.gridView.frame) + kLeftInset, 4, 16)];
    [sv addSubview:v2_v];
    
    v2_v.layer.masksToBounds = YES;
    v2_v.layer.cornerRadius = 2;
    v2_v.backgroundColor = themeColor;
    
    UILabel *v2_lb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(v2_v.frame) + 10, CGRectGetMinY(v2_v.frame), 100,30)];
    v2_lb.center = CGPointMake(v2_lb.center.x, v2_v.center.y);
    [sv addSubview:v2_lb];
    //
    NSMutableAttributedString *v2_lb_attr_str = [[NSMutableAttributedString alloc] initWithString:@"温馨提示"];
    [v2_lb_attr_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFang-SC-Medium" size:17.0f] range:NSMakeRange(0, 4)];
    [v2_lb_attr_str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:17.0f/255.0f green:17.0f/255.0f blue:17.0f/255.0f alpha:1.0f] range:NSMakeRange(0, 4)];
    v2_lb.attributedText = v2_lb_attr_str;
    
    self.wenxintishiLb = [[QMUILabel alloc] init];
    self.wenxintishiLb.backgroundColor = UIColor.whiteColor;
    self.wenxintishiLb.font = [UIFont systemFontOfSize:14];
    [sv addSubview:self.wenxintishiLb];
    self.wenxintishiLb.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 16, 16);
    self.wenxintishiLb.numberOfLines = 0;
    self.wenxintishiLb.layer.masksToBounds = YES;
    self.wenxintishiLb.layer.cornerRadius = 10;
    self.wenxintishiLb.text = @"";
    
}
- (void)qu_geng_xin_btn_action{
    
    Jiankang_fenxi_vc *vc= [[Jiankang_fenxi_vc alloc]init];
    vc.lastPage_bmi = self.current_bmi;
    vc.hidesBottomBarWhenPushed = YES;
    
    
    vc.deviceId = self.currentDevice.device_id;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)handleButtonEvent:(QMUIButton *)button {
    [self.popupByWindow showWithAnimated:YES];
  
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}
#pragma mark - ================== 调试用 ==================
- (void)xxx_action{
    Huati_taolun_fabu_vc *vc= [[Huati_taolun_fabu_vc alloc]init];
    vc.title = @"发布话题讨论";
    
    
    vc= [[Huati_guangchang_vc alloc]init];
    
    vc = Tuijian_vc.new;
    
    //    vc = Tiezi_fabu_vc.new;
    vc = Tiezi_xiangqing_vc.new;
    
    vc= [[Tiezi_pinglun_vc alloc]init];
    
    
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //    [self xxx_action];
}

#pragma mark - ================== 宝宝几个月计算 ==================
- (NSString *)bb_month{
    //创建两个日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [dateFormatter dateFromString:self.current_bmi.data.birthday];
    
    
    
    NSDate *endDate = [dateFormatter dateFromString:[self getCurrentDate]];
    
    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传：
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     */
    NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    //打印
    NSLog(@"%@",delta);
    //获取其中的"天"
    NSLog(@"%ld",delta.month);
    
    if (delta.month == 0) {
        return [NSString stringWithFormat:@"%ld天", delta.day];
    }
    return [NSString stringWithFormat:@"%ld个月", delta.month];
}
//获取当前时间
-(NSString *)getCurrentDate{
    NSDate * date = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init ];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString * dateStr = [dateFormatter stringFromDate:date];
    return dateStr;
}
- (NSAttributedString *)bb_title:(NSString *)raw_bb_title font:(UIFont *)font{
    NSMutableAttributedString *bb_title = [[NSMutableAttributedString alloc] initWithString:raw_bb_title];
    [bb_title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, raw_bb_title.length)];
    [bb_title addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0f] range:NSMakeRange(0, raw_bb_title.length)];
    return bb_title;
}
- (QMUIButton *)add_device_btn{
    if(_add_device_btn == nil)
    {
        _add_device_btn = [QDUIHelper generateLightBorderedButton];
        [_add_device_btn addTarget:self action:@selector(add_action) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _add_device_btn;
}

- (void)add_action{
    if ([self.bb_xq_lb.text isEqualToString:@"您还未添加设备"]) {
        // 添加设备
        CYLPlusDemoChildViewController *vc= [[CYLPlusDemoChildViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([self.bb_xq_lb.text isEqualToString:@"您的宝宝基本信息还未添加，为更好掌握宝宝健康状况，请及时添加！"]){
        // 添加bmi
        Jiankang_fenxi_vc *vc= [[Jiankang_fenxi_vc alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        
        vc.delegate = self;
        vc.deviceId = self.currentDevice.device_id;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}
- (void)updateWithBmiInfo:(Bmi_setBabyBmi *)info{
    self.current_bmi = info;
}
@end
